package com.sinoglobal.ningxia.activity.interestingGame;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.adapter.InteractionAnswerGdAdapter;
import com.sinoglobal.ningxia.beans.InteractionAnswerListItemsVo;
import com.sinoglobal.ningxia.beans.InteractionAnswerListVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.widget.MyDialog;
import com.sinoglobal.ningxia.widget.MyDialog.MyDialogListener;

/**
 * @author sbk
 * @createdate 2013-12-12 下午2:18:11
 * @Description: 答题中
 */
public class AnsweringActivity extends AbstractActivity implements
		OnClickListener, OnItemClickListener, MyDialogListener {

	private GridView aGridView;
	private TextView tvTitle, tvIndex, tvTime, tvAccuracy;
	private List<String> aListItem;
	// private List<AnswerInfo> answerInfos=new ArrayList<AnswerInfo>();
	private ArrayList<InteractionAnswerListItemsVo> aList;
	private int index = 0, yCount = 0, count; // 第几题
	private InteractionAnswerGdAdapter aAdapter;
	private Handler mhandler;
	private ProgressBar sPro, tPro, aPro;
	private String id;// 活动id
	private Timer timer;
	private int time = 30; // 倒计时
	private final int TIME = 2;
	private final int PROCESS = 1;
	private StringBuffer details; // 答题详情，用于服务器统计
	protected int acc;
	private MyDialog myDialog;
	private ItktAsyncTaskWithDialog task;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.interaction_answer_layout);

		// 获取屏幕信息
		int screenWidth = FlyApplication.widthPixels;
		int height = (int) (1.136 * screenWidth);
		LinearLayout bgLayout = (LinearLayout) findViewById(R.id.l10);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				screenWidth, height);
		bgLayout.setLayoutParams(params);
		aGridView = (GridView) findViewById(R.id.gv_id);
		tvTitle = (TextView) findViewById(R.id.text10);
		tvIndex = (TextView) findViewById(R.id.text2);
		tvTime = (TextView) findViewById(R.id.text3);
		tvAccuracy = (TextView) findViewById(R.id.text4);
		sPro = (ProgressBar) findViewById(R.id.view_progress);
		tPro = (ProgressBar) findViewById(R.id.view1);
		aPro = (ProgressBar) findViewById(R.id.view2);
		templateButtonRight.setVisibility(View.INVISIBLE);
		titleView.setText("答题");
		id = getIntent().getStringExtra("id");
		details = new StringBuffer();
		mhandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case PROCESS:
					if (index < aList.size()) {
						String accuracy = getString(R.string.accuracy);
						accuracy = MessageFormat.format(accuracy, acc);
						tvAccuracy.setText(accuracy);
						// tvAccuracy.setText("正确率：" + acc + "%");
						acc = verdict(index, msg.arg1);
						index++;
//						tvIndex.setText(index + 1 + "/" + count);
						tvIndex.setText(MessageFormat.format("{0}/{1}", index+1,count));
						sPro.setProgress(index + 1);
						aPro.setProgress(acc);
						tPro.setProgress(30);
						if (index == aList.size()) {
							tvIndex.setText(MessageFormat.format("{0}/{1}", index,count));
							sPro.setProgress(index);
							// 答完，把成绩带过去
							Intent intent = new Intent(AnsweringActivity.this,
									AnswerResultActivity.class);
							intent.putExtra("mList", aList);
							intent.putExtra("acc", acc);
							intent.putExtra("yCount", yCount);
							intent.putExtra("deti", details.toString());
							FlyUtil.intentForward(AnsweringActivity.this,
									intent);
							overridePendingTransition(R.anim.push_left_in,
									R.anim.push_left_out);
							if (timer != null) {
								timer.cancel();
							}
							AnsweringActivity.this.finish();
						} else {
							loadSubject(index);
							aAdapter.notifyDataSetChanged();

						}

					} else {

					}
					break;
				case TIME:
					tPro.setProgress(time);
					tvTime.setText(MessageFormat.format(
							getString(R.string.time_left), time));
					break;
				default:
					break;
				}
			}
		};
		aAdapter = new InteractionAnswerGdAdapter(this, mhandler);
		loadData();

	}

	/**
	 * @author sbk
	 * @createdate 2013-12-15 下午3:51:05
	 * @Description: 验证答案的正确性
	 * @param index2
	 * @param arg1
	 * @return
	 * 
	 */
	private int verdict(int index2, int arg1) {

		int d = 0;
		if (aList.get(index2).getAnswer_right().equalsIgnoreCase(getKey(arg1))) {// 假如对了
			yCount++;
		} else {
			aList.get(index2).setSelect(arg1);
			aList.get(index2).setError(true);
		}
		try {
			d = yCount * 100 / (index + 1);
		} catch (Exception e) {
			// TODO: handle exception
		}
		details.append(aList.get(index2).getId());
		details.append(aList.get(index2).getAnswer_right());
		details.append(getKey(arg1));
		details.append(",");
		return d;
		// return String.format("%10.2f%%", d);

	}

	/**
	 * @author sbk
	 * @createdate 2013-12-26 下午3:51:24
	 * @Description: 返回正确答案
	 * @param arg
	 * @return
	 * 
	 */
	private String getKey(int arg) {
		String res = "";
		switch (arg) {
		case 0:
			res = "a";
			break;
		case 1:
			res = "b";
			break;
		case 2:
			res = "c";
			break;
		case 3:
			res = "d";
			break;
		}
		return res;
	}

	private void loadData() {
		task = (ItktAsyncTaskWithDialog) new ItktAsyncTaskWithDialog<Void, Void, InteractionAnswerListVo>(
				getString(R.string.get_topic_list), true, true) {

			@Override
			public InteractionAnswerListVo before(Void... params)
					throws Exception {
				return RemoteImpl.getInstance().getAnswerList(id);
			}

			@Override
			public void after(InteractionAnswerListVo result) {
				if (Code.CODE_SUCCESS != result.getCode()) {
					showShortToastMessage(result.getMessage());
					return;
				}
				if (result.getList().size() > 0) {
					templateButtonLeft
							.setOnClickListener(AnsweringActivity.this);
					aList = result.getList();
					count = aList.size();
					tvIndex.setText(MessageFormat.format("1/{0}", count));
					sPro.setMax(count);
					tPro.setMax(30);
					aGridView.setOnItemClickListener(AnsweringActivity.this);
					loadSubject(index);
					aGridView.setAdapter(aAdapter);
				}
			}

			@Override
			public void exception() {
				// Auto-generated method stub

			}
		}.execute();
	}

	/**
	 * @author sbk
	 * @createdate 2013-12-15 下午1:37:04
	 * @Description: 加载kaoti
	 * @param i
	 * 
	 */
	private void loadSubject(int i) {
		aListItem = new ArrayList<String>();
		InteractionAnswerListItemsVo t = aList.get(i);
		tvTitle.setText(t.getAnswer_name());
		aListItem.add(t.getAaa());
		aListItem.add(t.getBbb());
		if (TextUtil.stringIsNotNull(t.getCcc())) {
			aListItem.add(t.getCcc());
		}
		if (TextUtil.stringIsNotNull(t.getDdd())) {
			aListItem.add(t.getDdd());
		}
		if ("1".equals(t.getType())) {
			aGridView.setNumColumns(2);
			aGridView.setVerticalSpacing(5);
		} else {
			aGridView.setNumColumns(1);
			aGridView.setVerticalSpacing(25);
		}
		aAdapter.setaListItem(aListItem, t.getType());
		if (timer != null) {
			timer.cancel();
		}
		time = 30;
		timer = new Timer();
		timer.schedule(new MyTask(), 0, 1000);
	}

	private class MyTask extends TimerTask {

		@Override
		public void run() {
			time--;
			if (time < 1) {
				Message msg = new Message();
				msg.what = PROCESS;
				msg.arg1 = -1;
				mhandler.sendMessage(msg);
			} else {
				mhandler.sendEmptyMessage(TIME);
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_but_left: // 返回
			showDialog();
			break;

		default:
			break;
		}
	}

	private void showDialog() {
		if (myDialog == null) {
			myDialog = new MyDialog(this).setTitle(getString(R.string.give_up_answer))
					.setPositiveButton(getString(R.string.btn_sure_text)).setNegativeButton(getString(R.string.btn_cancle));
			myDialog.tvMessage.setVisibility(View.GONE);
		}
		if (!myDialog.isShowing()) {
			myDialog.show();
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog();
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		loadSubject(index);
		aAdapter.notifyDataSetChanged();

	}

	@Override
	public void doPositive() {
		// Auto-generated method stub
		if (timer != null) {
			System.out.println("timer is cancell");
			timer.cancel();
		}
		if (!task.isCancelled()) {
			System.out.println("task is cancell");
			task.cancel(true);
		}
		finish();
	}

	@Override
	public void doNegative() {
		// Auto-generated method stub

	}

	/**
	 * @author sbk
	 * @createdate 2013-12-26 下午3:51:24
	 * @Description: 返回正确答案
	 * @param arg
	 * @return
	 * 
	 */
	private int getNum(String arg) {
		int res = -1;
		if ("a".equalsIgnoreCase(arg)) {
			res = 0;
		} else if ("b".equalsIgnoreCase(arg)) {
			res = 1;
		} else if ("c".equalsIgnoreCase(arg)) {
			res = 2;
		} else if ("d".equalsIgnoreCase(arg)) {
			res = 3;
		}
		return res;
	}
}
